<template>
    <div>
        <global-tables
            @handleAllSelect="handleAllSelect"
            @changePage="handleChangePage"
            :list="list"
            :total="total"
            :loading="loading"
            :columns="columns"
            :current="search.pageindex"
        >
            <Form :model="search" :label-width="80">
                <div class="table-top-wrap">
                    <div>
                        <div>
                            <Button v-if="type == 1" class="features-btn" @click="handleBtnClick(null,'add')">
                                <Icon type="md-add" size="18" />新建
                            </Button>
                            <Button v-if="type == 1" class="features-btn btn-auto-m" @click="handleBtnClick(null,'delete')" style="margin-right:10px">
                                <Icon type="md-trash" size="17" />删除
                            </Button>
                            <Button class="features-btn btn-auto-m" @click="$router.go(-1)" style="margin-left:0px;">
                                <Icon type="ios-arrow-back" size="17" />返回
                            </Button>
                        </div>
                    </div>
                </div>
            </Form>
        </global-tables>
        <Modal :mask-closable="false" v-model="isModal" :title="ModalTitle" width="600">
            <div v-if="isModal">
                <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="100">
                    <Row>
                        <i-col :lg="{ span: 12}">
                            <FormItem class="demo-auto-complete-from" label="选择商品" prop="PID">
                                <AutoComplete
                                    v-model="defaultAutoComplete"
                                    icon="ios-search"
                                    @on-change="handleSearchAutoComplete"
                                    placeholder="请选择商品"
                                    style="width:400px"
                                >
                                    <div class="demo-auto-complete-wrap">
                                        <div class="demo-auto-complete-item" v-for="(item,index) in autoComplete" :key="index">
                                            <Option @click.native="handleAutoCompleteSearch(item)" :value="item.ProName" :key="item.ID">
                                                <span class="demo-auto-complete-title">{{ item.ProName }}</span>
                                                <span class="demo-auto-complete-title" v-if="item.TID == 0">&nbsp;(单品)</span>
                                                <span class="demo-auto-complete-title" v-else>&nbsp;&nbsp;({{ item.SpecName }})</span>
                                                <span class="demo-auto-complete-count">{{item.FactoryShortName }}</span>
                                            </Option>
                                        </div>
                                    </div>
                                </AutoComplete>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row v-if="isSpecifications">
                        <i-col :lg="{ span: 24}">
                            <FormItem label="规格">
                                <span v-if="Specifications.TID==0">单品</span>
                                <span v-else-if="Specifications.PSID==0">单品</span>
                                <span v-else-if="Specifications.PSID>0">{{Specifications.PSName}}</span>
                                <span v-else>{{Specifications.SpecName}}</span>
                            </FormItem>
                        </i-col>
                        <i-col :lg="{ span: 24}">
                            <FormItem label="生产厂家">
                                <span>{{Specifications.FactoryName}}</span>
                            </FormItem>
                        </i-col>
                        <i-col :lg="{ span: 24}">
                            <FormItem label="厂家货号">
                                <span>{{Specifications.ProCode}}</span>
                            </FormItem>
                        </i-col>
                        <i-col :lg="{ span: 24}">
                            <FormItem label="SKU">
                                <span>{{Specifications.SKU}}</span>
                            </FormItem>
                        </i-col>
                        <i-col :lg="{ span: 24}">
                            <FormItem label="进货单位">
                                <span v-if="Specifications.TID==0">1{{Specifications.UnitBuy}}={{Specifications.UnitCount}}{{Specifications.UnitSales}}</span>
                                <span v-else-if="Specifications.PSID>=0">1{{Specifications.UnitBuy}}={{Specifications.UnitCount}}{{Specifications.UnitSales}}</span>
                                <span v-else>1{{Specifications.SpecUnitBuy}}={{Specifications.SpecUnitCount}}{{Specifications.SpecUnitSales}}</span>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span:19}">
                            <FormItem label="进货价" prop="Cost">
                                <input
                                    type="number"
                                    oninput="if(value.length>13)value=value.slice(0,13)"
                                    v-model="formItem.Cost"
                                    class="style-input"
                                    placeholder="请输入进货价"
                                />
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 19}">
                            <FormItem label="生产日期" prop="ProductionDate">
                                <DatePicker type="date" v-model="formItem.ProductionDate" placeholder="请选择日期" style="width:100%"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span:19}">
                            <FormItem label="数量" prop="Count">
                                <input
                                    type="number"
                                    oninput="if(value.length>13)value=value.slice(0,13)"
                                    v-model="formItem.Count"
                                    class="style-input"
                                    placeholder="请输入数量"
                                />
                            </FormItem>
                        </i-col>
                    </Row>
                </Form>
            </div>
            <div slot="footer">
                <Button size="large" @click="handleClose">取消</Button>
                <Button type="primary" size="large" @click="handleSubmit('formItem')">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
/**
 *  采购单明细列表
 */
import Api from './service';
import GlobalTables from '@/components/GlobalTables';

export default {
    name: 'PurchaseListDetail',
    components: {
        GlobalTables
    },
    data() {
        const validatorPID = (rule, value, callback) => {
            setTimeout(() => {
                if (this.formItem.PID == '' || !this.formItem.PID) {
                    callback(new Error('请选择商品'));
                } else {
                    callback();
                }
            }, 100);
        };
        return {
            list: [],
            data4: [],
            total: 0,
            itemId: 0,
            productsList: [],
            loading: true,
            type: '',
            defaultAutoComplete: '',
            PSIDlist: [],
            autoComplete: [],
            isModal: false,
            allSelectArr: null,
            isSpecifications: false,
            Specifications: '',
            ModalTitle: '新建采购单明细',
            formItem: this.initFormItem(),
            ruleValidate: {
                ArriveTime: [
                    {
                        required: true,
                        message: '请选择日期',
                        trigger: 'change',
                        pattern: /.+/
                    }
                ],
                PID: [
                    {
                        required: true,
                        validator: validatorPID
                    }
                ],
                Cost: [
                    {
                        required: true,
                        message: '请输入不可为空',
                        trigger: 'change'
                    }
                ],
                Count: [
                    {
                        required: true,
                        message: '请输入不可为空',
                        trigger: 'change'
                    }
                ],
                OrderType: [
                    {
                        required: true,
                        message: '请选择所属供应商',
                        trigger: 'change'
                    }
                ],
                ProductionDate: [
                    {
                        required: true,
                        message: '请选择日期',
                        trigger: 'change',
                        pattern: /.+/
                    }
                ]
            },
            search: {
                keyword: '',
                pageindex: 1,
                pagesize: 10
            },
            columns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '商品名称',
                    render: (h, params) => {
                        const { PSID, PName } = params.row;
                        if (PSID == 0) {
                            return h('div', [h('p', {}), PName]);
                        } else {
                            return h('div', [h('p', {}), `${PName}`]);
                        }
                    }
                },
                {
                    title: '生产厂家',
                    key: 'FactoryName'
                },
                {
                    title: '规格名称',
                    width: 150,
                    render: (h, params) => {
                        const { PSID, PSName } = params.row;
                        if (PSID == 0) {
                            return h('div', [h('p', {}), '单品']);
                        } else {
                            return h('div', [h('p', {}), PSName]);
                        }
                    }
                },
                {
                    title: '进货单位',
                    width: 150,
                    render: (h, params) => {
                        const { UnitCount, UnitSales, UnitBuy } = params.row;
                        return h('div', [h('p', {}), `1${UnitBuy}=${UnitCount}${UnitSales}`]);
                    }
                },
                {
                    title: '进货价',
                    key: 'Cost',
                    width: 100
                },
                {
                    title: '进货数量',
                    key: 'Count',
                    width: 100
                },
                {
                    title: '小计',
                    key: 'SubTotal',
                    width: 100
                },
                {
                    title: '操作',
                    width: 80,
                    align: 'left',
                    render: (h, params) => {
                        //const { isEdit, isDetail } = this;
                        //const { State } = params.row;
                        return h('div', [
                            //isEdit &&
                            this.type == 1 &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            background: '#5ab1ef',
                                            border: 'none',
                                            margin: '5px 2px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(params.row, 'detail');
                                            }
                                        }
                                    },
                                    '修改'
                                )
                        ]);
                    }
                }
            ]
        };
    },
    methods: {
        /* 表格数据请求 */
        getTablesListData() {
            const data = this.search;
            data.oid = this.$route.params.id;
            Api.getTablesListDetail(data).then(res => {
                this.list = res.data.rows;
                this.loading = false;
                this.total = res.data.records;
            });
        },
        handleSearchAutoComplete(data) {
            this.formItem.PID = null;
            this.formItem.PSID = null;
            this.isSpecifications = false;
            this.Specifications = '';
            this.formItem.PName = '';
            this.formItem.PSName = '';
            Api.handleSearchProduct({
                keyword: data
            }).then(res => {
                this.autoComplete = res.data;
            });
        },
        /* 表格查询 */
        handleSearch() {
            this.loading = true;
            this.getTablesListData();
        },
        handleAutoCompleteSearch(data) {
            this.formItem.PID = data.ID;
            this.formItem.PSID = data.TID;
            this.formItem.PName = data.ProName;
            this.formItem.PSName = data.SpecName;
            this.formItem.FactoryID = data.FactoryID;
            this.formItem.FactoryName = data.FactoryName;
            this.isSpecifications = true;
            this.Specifications = data;
            if (data.TID > 0) {
                this.formItem.UnitBuy = data.SpecUnitBuy;
                this.formItem.UnitCount = data.SpecUnitCount;
                this.formItem.UnitSales = data.SpecUnitSales;
            } else {
                this.formItem.UnitBuy = data.UnitBuy;
                this.formItem.UnitCount = data.UnitCount;
                this.formItem.UnitSales = data.UnitSales;
            }
        },
        /* 对话框 */
        handleBtnClick(item, type) {
            if (type == 'add') {
                this.isModal = true;
                this.PSIDlist = [];
                this.formItem = this.initFormItem();
                this.isSpecifications = false;
                this.ModalTitle = '新建采购单明细';
                this.Specifications = '';
                this.defaultAutoComplete = '';
                Api.handleSearchProduct().then(res => {
                    this.autoComplete = res.data;
                });
            } else if (type == 'detail') {
                this.isSpecifications = true;
                this.isModal = true;
                this.ModalTitle = '修改采购单明细';
                Api.handleSearchProduct().then(res => {
                    this.autoComplete = res.data;
                    Api.GetForm({
                        id: item.ID
                    }).then(res => {
                        this.defaultAutoComplete = res.data.PName;
                        this.formItem = {
                            ...res.data,
                            Cost: res.data.Cost + '',
                            Count: res.data.Count + '',
                            state: this.$route.params.type
                        };
                        this.Specifications = res.data;
                    });
                });
            } else if (type === 'delete') {
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要删除吗`,
                        onOk: () => {
                            Api.deleteItemDetail({
                                ids: this.allSelectArr,
                                state: this.$route.params.type
                            }).then(res => {
                                if (res.state == 'success') {
                                    this.$Message.success(res.message);
                                    this.allSelectArr = '';
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info('取消成功');
                        }
                    });
                } else {
                    this.$Message.error('请先选择需要操作的记录');
                }
            }
        },
        /* 表格分页方法 */
        handleChangePage(type, page) {
            this.loading = true;
            if (type == 'page') {
                this.search.pageindex = page;
                this.getTablesListData();
            } else {
                this.search.pagesize = page;
                this.getTablesListData();
            }
        },
        /* 复选框选中 */
        handleAllSelect(list) {
            let arr = [];
            for (let item in list) {
                arr.push(list[item].ID);
                arr.join(',');
            }
            arr = arr.join(',');
            this.allSelectArr = arr;
        },
        /* 提交 */
        handleSubmit(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    const data = this.formItem;
                    Api.addTablesItemDetail(data).then(res => {
                        if (res.state == 'success') {
                            this.$Message.success('操作成功');
                            this.loading = true;
                            this.isModal = false;
                            this.getTablesListData();
                        } else {
                            this.$Message.error(res.message);
                        }
                    });
                }
            });
        },
        /* 关闭对话框 */
        handleClose() {
            this.isModal = false;
        },
        /* 表单数据 */
        initFormItem() {
            return {
                PID: '',
                Remark: '',
                OrderType: '1',
                PSID: '',
                Cost: 0,
                Count: 0,
                OrderID: this.$route.params.id,
                OrderCode: this.$route.params.code,
                State: 0,
                FactoryID: '',
                FactoryName: '',
                PName: null,
                ID: '0',
                ProductionDate: ''
            };
        }
    },
    mounted() {
        /* 列表请求 */
        const { id, type } = this.$route.params;
        this.type = type;
        if (this.type != 1) {
            this.columns.pop();
        }
        this.search.keyword = id;
        this.getTablesListData();
    }
};
</script>

<style lang="less" scoped>
.demo-auto-complete-wrap {
    top: 100px;
    height: 300px;
    overflow-y: scroll;
}
.demo-auto-complete-item {
    padding: 4px 0;
}
.demo-auto-complete-group {
    font-size: 12px;
    padding: 4px 6px;
}
.demo-auto-complete-group span {
    color: #666;
    font-weight: bold;
}
.demo-auto-complete-group a {
    float: right;
}
.demo-auto-complete-count {
    float: right;
    color: #999;
}
.demo-auto-complete-more {
    display: block;
    margin: 0 auto;
    padding: 4px;
    text-align: center;
    font-size: 12px;
}
</style>

